//
//  PKDrawingLineView.m
//  PDFKitTest
//
//  Created by Emo, on 2024/1/23.
//

#import "PKDrawingLineView.h"
#import "PKPDFAnnotation.h"
#import "UIBezierPath+PDFDrawing.h"
#import "PKDrawingToolsView.h"

@interface PKDrawingLineView () <PKDrawingToolsDelegate>
{
    CGPoint currentPoint; // 当前触摸点
    CGPoint previousPointOld; // 上一个触摸点
    CGPoint previousPointNew; // 新的触摸点
}
// private properties
@property (nonatomic, strong) UIColor *lineColor;
@property (nonatomic, assign) CGFloat lineWidth;
@property (nonatomic, assign) CGFloat lineAlpha;

/** 绘线路径*/
@property (nonatomic, strong) UIBezierPath * drawPath;
/** PDF文档当前页*/
@property (strong, nonatomic) PDFPage *currentPage;
/** 当前移动手指绘制的标注*/
@property (nonatomic, strong) PKPDFAnnotation *moveAnnotation;
/** 操作工具条*/
@property (nonatomic, strong) PKDrawingToolsView * toolsView;
/** 撤销按钮数据源*/
@property (nonatomic, strong) NSMutableArray * lastAnnotations;
/** 反撤销按钮数据源*/
@property (nonatomic, strong) NSMutableArray * nextAnnotations;

@end

@implementation PKDrawingLineView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    self.lineColor = kDefaultLineColor;
    self.lineWidth = kDefaultLineWidth;
    self.lineAlpha = kDefaultLineAlpha;
    
    self.backgroundColor = [UIColor clearColor];
    
    [self addSubview:self.toolsView];
}


#pragma mark -- public --
- (BOOL)needSave {
    return (self.lastAnnotations.count>0) ? YES : NO;
}

/** 清空所有绘图*/
- (void)cleanAllAnnotations {
    // 遍历移除所有标注
    for (PKPDFAnnotation *annotation in self.lastAnnotations) {
        [annotation.page removeAnnotation:annotation];
    }
    // 清空撤销数组
    [self.lastAnnotations removeAllObjects];
    // 清空反撤销数组
    [self.nextAnnotations removeAllObjects];
    // 更新工具栏按钮状态
    [self updateToolsViewStatus];
}


#pragma mark -- UIResponder --
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取touch
    UITouch *touch = touches.anyObject;
    if (![touch.view isEqual:self]) {
        return;
    }
    // 获取开始时的上一次触摸点
    previousPointNew = [touch previousLocationInView:self];
    // 获取当前触摸点
    currentPoint = [touch locationInView:self];
    // 获取触摸点所在PDF页
    self.currentPage = [self.pdfView pageForPoint:previousPointNew nearest:YES];
    // 将触摸点转化为当前页的触摸点
    CGPoint currentPagePoint = [self.pdfView convertPoint:previousPointNew toPage:self.currentPage];
    // 创建PDF贝塞尔曲线(每次都新建曲线)
    self.drawPath = [UIBezierPath bezierPath];
    self.drawPath.lineCapStyle = kCGLineCapRound;
    self.drawPath.lineJoinStyle = kCGLineJoinRound;
    self.drawPath.lineWidth = self.lineWidth;
    [self.drawPath moveToPoint:currentPagePoint];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取touch
    UITouch *touch = touches.anyObject;
    if (![touch.view isEqual:self]) {
        return;
    }
    // 记录上一个触摸点
    previousPointOld = previousPointNew;
    // 获取移动时的上一次触摸点
    previousPointNew = [touch previousLocationInView:self];
    // 获取当前触摸点
    currentPoint = [touch locationInView:self];
    // 将触摸点转化为当前页的触摸点
    CGPoint currentPagePointOld = [self.pdfView convertPoint:previousPointOld toPage:self.currentPage];
    CGPoint currentPagePointNew = [self.pdfView convertPoint:previousPointNew toPage:self.currentPage];
    CGPoint currentPagePointCurrent = [self.pdfView convertPoint:currentPoint toPage:self.currentPage];
    // 添加路径
    [self.drawPath addPathPreviousPreviousPoint:currentPagePointOld withPreviousPoint:currentPagePointNew withCurrentPoint:currentPagePointCurrent];
    
    // 移动时添加批注，实现手指滑动的过程中，有曲线显示
    if (self.moveAnnotation == nil) {
        CGRect bounds = [self.currentPage boundsForBox:self.pdfView.displayBox];
        self.moveAnnotation = [[PKPDFAnnotation alloc] initWithBounds:bounds forType:PDFAnnotationSubtypeInk withProperties:nil];
    }
    self.moveAnnotation.color = self.lineColor;
    self.moveAnnotation.path = self.drawPath;
    [self.currentPage addAnnotation:self.moveAnnotation];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获取touch
    UITouch *touch = touches.anyObject;
    if (![touch.view isEqual:self]) {
        return;
    }
    if (!self.moveAnnotation) {
        return;
    }
    // 移除移动过程中的标注
    [self.currentPage removeAnnotation:self.moveAnnotation];
    // 停止触摸，添加最终的曲线标注
    CGRect bounds = [self.currentPage boundsForBox:self.pdfView.displayBox];
    PKPDFAnnotation *annotation = [[PKPDFAnnotation alloc] initWithBounds:bounds forType:PDFAnnotationSubtypeInk withProperties:nil];
    annotation.color = self.lineColor;
    annotation.path = self.drawPath;
    [self.currentPage addAnnotation:annotation];
    
    // 再撤销数组中添加标注对象
    [self.lastAnnotations addObject:annotation];
    // 更新工具栏按钮状态
    [self updateToolsViewStatus];
    NSLog(@"停止批注个数：%ld", [self.currentPage annotations].count);
}

// 更新工具栏按钮状态
- (void)updateToolsViewStatus {
    [self.toolsView setLastButtonSelected:(self.lastAnnotations.count > 0) ? YES : NO];
    [self.toolsView setNextButtonSelected:(self.nextAnnotations.count > 0) ? YES : NO];
}

#pragma mark -- delegate --
- (void)toolsView:(PKDrawingToolsView *)toolsView didClickLastButton:(UIButton *)lastBtn {
    if (self.lastAnnotations.count == 0) {
        return;
    }
    // 获取最后一个标注对象
    PKPDFAnnotation *annotation = self.lastAnnotations.lastObject;
    // 标注所在页移除标注
    [annotation.page removeAnnotation:annotation];
    // 撤销数组移除元素
    [self.lastAnnotations removeObject:annotation];
    // 发撤销数据添加元素
    [self.nextAnnotations addObject:annotation];
    // 更新工具栏按钮状态
    [self updateToolsViewStatus];
}

- (void)toolsView:(PKDrawingToolsView *)toolsView didClickNextButton:(UIButton *)nextBtn {
    if (self.nextAnnotations.count == 0) {
        return;
    }
    // 获取最后一个标注对象
    PKPDFAnnotation *annotation = self.nextAnnotations.lastObject;
    // 标注所在页移除标注
    [annotation.page addAnnotation:annotation];
    // 撤销数组添加元素
    [self.lastAnnotations addObject:annotation];
    // 发撤销数据移除元素
    [self.nextAnnotations removeObject:annotation];
    // 更新工具栏按钮状态
    [self updateToolsViewStatus];
}

- (void)toolsView:(PKDrawingToolsView *)toolsView didClickColorButton:(NSString *)colorHex {
    self.lineColor = HexColor(colorHex);
}

- (void)toolsView:(PKDrawingToolsView *)toolsView didClickLineButton:(NSInteger)lineSize {
    self.lineWidth = lineSize;
}


#pragma mark -- lazy --
- (PKDrawingToolsView *)toolsView {
    if (!_toolsView) {
        _toolsView = [[PKDrawingToolsView alloc] initWithFrame:CGRectMake(20, self.height-120, self.width-40, 80)];
        _toolsView.layer.cornerRadius = 40;
        _toolsView.layer.masksToBounds = YES;
        _toolsView.delegate = self;
    }
    return _toolsView;
}

- (NSMutableArray *)lastAnnotations {
    if (!_lastAnnotations) {
        _lastAnnotations = [NSMutableArray arrayWithCapacity:1];
    }
    return _lastAnnotations;
}

- (NSMutableArray *)nextAnnotations {
    if (!_nextAnnotations) {
        _nextAnnotations = [NSMutableArray arrayWithCapacity:1];
    }
    return _nextAnnotations;
}

@end
